package com.tc.gateway.tunnel;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;


public class TcpTunnelServer implements TunnelOutput, TunnelServer {
	
	OutputStream stream;
	List<Tunnel> tunnels = new LinkedList<Tunnel>();
	short port;
	ServerSocket ss;

	public TcpTunnelServer(final OutputStream stream, final short p) {
		super();
		this.port = p;

		this.stream = stream;
	
		
	}
	/* (non-Javadoc)
	 * @see com.tc.zigbee.tunnel.TunnelServer#started()
	 */
	public boolean started(){
		return ts != null;
	}
	/* (non-Javadoc)
	 * @see com.tc.assistance.tunnel.TunnelOutput#write(byte[], int, int)
	 */
	/* (non-Javadoc)
	 * @see com.tc.zigbee.tunnel.TunnelServer#write(byte[], int, int)
	 */
	public void write(byte[] buffer, int offset, int count){
		if(!started())
			return;
		for(Tunnel t : tunnels)
			t.write(buffer, offset, count);
	}
	/* (non-Javadoc)
	 * @see com.tc.zigbee.tunnel.TunnelServer#stop()
	 */
	public void stop(){
		try {
			ss.close();

		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		ss = null;
		ts.interrupt();
		ts = null;
		for(Tunnel t : tunnels){
			t.interrupt();
		}
	}
	Thread ts;
	/* (non-Javadoc)
	 * @see com.tc.zigbee.tunnel.TunnelServer#start()
	 */
	public void start(){
		ts = new Thread(){

			@Override
			public void run() {
				
				super.run();
				
				try {
					ss = new ServerSocket(port);
					while(true){
						Socket s = ss.accept();
						Tunnel t = new Tunnel(stream, s, TcpTunnelServer.this);
						tunnels.add(t);
						t.start();
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					System.out.println(e.getMessage());
				}
			}
			
		};
		ts.start();
	}

}
